package com.meteor.controller;

import com.github.pagehelper.PageInfo;
import com.meteor.pojo.Book;
import com.meteor.pojo.Type;
import com.meteor.service.BookService;
import com.meteor.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    @Resource
    private TypeService typeService;

    // 图书查询显示
    @GetMapping("/book")
    public String book(Model model) {
        PageInfo<Book> info = bookService.selectBook(1, null);
        List<Type> types = typeService.selectAllType();
        List<Book> books = info.getList();
        model.addAttribute("types",types);
        model.addAttribute("books",books);
        model.addAttribute("info", info);
        return "back/bookInfo";
    }


    // 图书查询（可模糊全局搜索）
    @RequestMapping("/bookPage")
    @ResponseBody
    public PageInfo<Book> selectBook(Integer pageNum,String bookName) {
        if(bookName.equals("")) {
            bookName = null;
        }
        PageInfo<Book> books = bookService.selectBook(pageNum, bookName);
        return books;
    }

    // 图书新增
    @GetMapping("/insert")
    public String insertBook(Book book,String typeName,Model model) {
        book.setSellCount(0);
        Type type = typeService.selectTypeByName(typeName);
        book.setTypeId(type.getId());
        book.setCreateTime(new Date());
        int i = bookService.insertBook(book);
        if( i > 0) {
            model.addAttribute("message", "图书添加成功");
        }else {
            model.addAttribute("message", "图书添加失败");
        }
        return "forward:/book/book";
    }

//    ----------------------------------------------前端首页-------------------------------------------------------

    // 随机查询5本书放在轮播图中
    // 最新、最热、最高图书展示
    @GetMapping("/randBook")
    public String selectBookRand(Model model) {
        // 随机查询5本书
        List<Book> bookRands = bookService.selectBookRand();
        model.addAttribute("bookRands", bookRands);

        // 按时间倒序全部书籍
        List<Book> bookTimes = bookService.selectBookByTime();
        model.addAttribute("bookTimes", bookTimes);

        // 按评分高低倒序查询
        List<Book> bookMarks = bookService.selectBookByMark();
        model.addAttribute("bookMarks", bookMarks);

        //按销量高低倒序查询
        List<Book> bookSells = bookService.selectBookBySell();
        model.addAttribute("bookSells", bookSells);
        return "front/home";
    }
}
